import Vue from 'vue'
// Vue指令：给当前元素添加拖动效果
Vue.directive('draggable', {
  inserted (el, binding) {
    console.log(el)
    // 只支持点击头部拖动
    const dragDom = el.querySelector('.ry_draggable')
    // dragDom.style.cursor = 'move'
    dragDom.style.cursor = 'url(/img/drag_.cur)'

    dragDom.onmousedown = (e) => {
      // [ˌprɒpə'ɡeɪʃ(ə)n]
      e.stopPropagation()
      const Rect = el.getBoundingClientRect()
      const domToTop = Rect.top // dom 的顶边到视口顶部的距离
      const domToLeft = Rect.left // dom 的左边到视口左边的距离
      const domToBottom = document.body.clientHeight - Rect.bottom // dom 的底边到视口底部的距离
      const domToRight = document.body.clientWidth - Rect.right // dom 的右边到视口右边的距离

      // clientX/Y： 鼠标相对窗口位置
      // offsetLeft/Top： 距离最近有定位的DOM的距离
      const startX = e.clientX
      const startY = e.clientY
      const relativeX = el.offsetLeft
      const relativeY = el.offsetTop

      document.onmousemove = (_e) => {
        _e.stopPropagation()
        // 鼠标移动距离
        const moveX = _e.clientX - startX
        const moveY = _e.clientY - startY
        // 怎么判断当前元素是否已经越界? 首先移动都是基于元素点击时相对位置（relativeX/Y）
        // 1.通过getBoundingClientRect获取当前DOM 距离边界的距离
        // 2.移动的距离和边界距离做一个比较
        if (moveX > domToRight) {
          // 太靠右
          el.style.left = `${relativeX + domToRight}px`
        } else if (-moveX > domToLeft) {
          // 太靠左
          el.style.left = `${relativeX - domToLeft}px`
        } else {
          el.style.left = `${moveX + relativeX}px`
        }
        if (-moveY > domToTop) {
          // 太靠上
          el.style.top = `${relativeY - domToTop}px`
        } else if (moveY > domToBottom) {
          // 太靠下
          el.style.top = `${relativeY + domToBottom}px`
        } else {
          el.style.top = `${moveY + relativeY}px`
        }
        // 优化：阻止默认事件 防止拖动时选中其他元素出现蓝底
        return false
      }
      document.onmouseup = (_e) => {
        _e.stopPropagation()
        document.onmousemove = null
        document.onmouseup = null
      }
    }
  }
})
